# -*- coding: utf-8 -*-

import functions

def index(req, **args):
 return functions.redirect(req, 'stat')

def sign(req, **data):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 state = u'Авторизация'
 if functions.get_cookie_id(req) > 0:
  return functions.redirect(req, 'stat')
 elif not data:
  functions.db.close()
  return functions.use_template(req, 'sign.html', ip=req.get_remote_host(), curstate=state,\
  menu=functions.make_menu(req, 'lpanel.html', [(state, None)]))
 else:
  ID = functions.login(req, data)
  if ID > 0:
   functions.set_cookie_id(req, ID)
   functions.db.close()
   return functions.redirect(req, 'stat')
  else:
   functions.db.close()
   return functions.use_template(req, 'sign.html', msg=u'неправильный логин или пароль',\
   email=data.get('MailSign', '').replace('"', ''), ip=req.get_remote_host(), curstate=state,\
   menu=functions.make_menu(req, 'lpanel.html', [(state, None), (u'Справка', 'help')]))

def logout(req, **args):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 h = req.headers_in
 if 'Cookie' in h.keys():
  c = functions.Cookie()
  c.load(h['Cookie'])
  try: ID, key = c['nauthskey'].value.split('x')
  except: key = '000000'
 else: key = '000000'
 functions.db.query('delete from cookies where skey=%s', (key, ))
 functions.db.commit()
 req.headers_out["Set-Cookie"] = 'nauthskey='
 functions.db.close()
 return functions.redirect(req, 'sign')

def stat(req, **args):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 return functions.show_stat(req, user, **args)

#def dirr(req):
 #return repr(dir(req))

def inet_on(req, f=86400):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 res = user.inet('1', int(f))
 functions.update_tariffs(functions.db)
 functions.update_firewall(functions.db)
 functions.db.close()
 return res

def inet_off(req, f=86400):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 res = user.inet('0', int(f))
 functions.update_tariffs(functions.db)
 functions.update_firewall(functions.db)
 functions.db.close()
 return res

#def style(req):
 #req.content_type = 'text/css'
 #return functions.use_template(req, 'style.css')

#def jscript(req):
 #req.content_type = 'text/javascript'
 #return functions.use_template(req, 'script.js')

#def screen(req):
 #req.content_type = 'image/png'
 #fp=file(functions.path.join(functions.path.dirname(req.filename), 'templates', 'screen.png'))
 #p=fp.read()
 #fp.close()
 #return p

def chpass(req, old='', new='', new2=''):
 functions.db = functions.mysql_db()
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 state = u'Смена пароля'
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 menu = functions.gmenu()
 menu[3][1] = None
 menu = functions.make_menu(req, 'lpanel.html', menu)
 if old or new or new2:
  ID2 = functions.login(req, {'MailSign': user.mail, 'PassSign': old})
  if ID == ID2:
   if (new == new2):
    if len(new) > 3:
     functions.db.query('update users set PASS=%s where ID=%s', (functions.hash_passwd(new), ID))
     functions.db.commit()
     functions.db.close()
     return functions.redirect(req, 'stat?msg=Password%20changed.')
    else: msg = u'Новый пароль слишком короткий'
   else: msg = u'Пароли не совпадают'
  else: msg = u'Неверный пароль'
  functions.db.close()
  return functions.use_template(req, 'chpass.html', curstate=state, menu=menu, msg=msg)
 else:
  functions.db.close()
  return functions.use_template(req, 'chpass.html', curstate=state, menu=menu)

def users(req, **params):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 menu = functions.gmenu()
 menu[2][1] = None
 menu = functions.make_menu(req, 'lpanel.html', menu)
 smenu = functions.make_menu(req, 'tpanel.html', [[u'Список', None], \
 [u'Добавить пользователя', 'adduser']])
 if user.is_admin():
  us = functions.db.query('select users.ID,users.login,MAIL,PASS,BALANCE,prepaid_packets.prepaid,IP,STATUS,'+\
  'REGDATE,COMMENT,NETUNTIL,LASTACT,description,tariffs.price,users.lastabon+tariffs.interval '+\
  'from users,tariffs,prepaid_packets where '+\
  'tariffs.id=users.TARIF and prepaid_packets.userid=users.ID and prepaid_packets.traf_id=1 order by LASTACT desc').fetchall()
  uu = u''
  for u in us:
   ID, login, mail, p, balance, prepaid, ip, st, datereg, comment, netuntil, lastact, tarif, price, prepaidfor = u
   if balance < 0: bc = 'red'
   else: bc = 'green'
   if st == 0: ic = 'grey'
   else: ic = 'green'
   balance = '%0.2f' % (balance, )

   if price > 0.01:
    prepaidfor = u'до %s' % functions.mytime(prepaidfor)
   else: prepaidfor = u''
   s = functions.inet_status(st, netuntil)
   uu += functions.use_template(req, 'user.html', uid=str(ID), login=login, mail=mail,\
   balance=balance, prepaid=functions.traffic(prepaid), ip=ip, netstat=s, datereg=str(datereg), \
   comment=functions.db.decode(comment), lastact=functions.lastact(lastact), \
   tarif=tarif, ic=ic, bc=bc, prepaidfor=prepaidfor).decode(functions.enc)
  functions.db.close()
  return functions.use_template(req, 'users.html', users=uu,\
  curstate=u'Список юзеров', menu=menu, submenu=smenu)
 else:
  functions.db.close()
  return functions.use_template(req, 'admin-only.html', menu=menu,\
  curstate=u'Список юзеров', submenu=smenu)

def su(req, suid=0):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 menu = functions.gmenu()
 menu[1][1] = None
 menu = functions.make_menu(req, 'lpanel.html', menu)
 if user.is_admin():
  functions.set_cookie_id(req, suid)
  functions.db.close()
  return functions.redirect(req, 'stat')
 else:
  functions.db.close()
  return functions.use_template(req, 'admin-only.html', menu=menu, \
  curstate=u'пошёл нахуй отсюда!')

def pay(req, uid='0', paysum='0', comment='?'):
 functions.db = functions.mysql_db()
 uid = int(uid)
 paysum = float(paysum)
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 menu = functions.gmenu()
 menu = functions.make_menu(req, 'lpanel.html', menu)
 if user.is_admin():
  if paysum == 0:
   puser = functions.user(req, uid)
   functions.db.close()
   return functions.use_template(req, 'pay.html', uid=str(puser.ID), \
   mail=puser.mail, ip=puser.ip, curstate=u'Пополнение баланса', menu=menu)
  else:
   # proceed payment
   functions.pay(uid, ID, paysum, comment)
   functions.update_tariffs(functions.db)
   functions.update_firewall(functions.db)
   functions.db.commit()
   functions.db.close()
   return functions.redirect(req, 'users')
 else:
  functions.db.close()
  return functions.use_template(req, 'admin-only.html', menu=menu, \
  curstate=u'пошёл нахуй отсюда!')

def chtarif(req, uid='0', tarif='-1'):
 functions.db = functions.mysql_db()
 uid = int(uid)
 tarif = int(tarif)
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 menu = functions.gmenu()
 menu = functions.make_menu(req, 'lpanel.html', menu)
 if user.is_admin():
  if (tarif == -1) or (uid == 0):
   puser = functions.user(req, uid)
   c = functions.db.query('select id,description from tariffs order by description')
   tarifs = [[functions.db.decode(i) for i in j] for j in c.fetchall()]
   for i in tarifs: 
    if i[0] == int(puser.tarif): i[1] = '<option selected value="%s">%s</option>' % tuple(i)
    else: i[1] = '<option value="%s">%s</option>' % tuple(i)
   tarifs = '\n'.join([i[1] for i in tarifs])
   functions.db.close()
   return functions.use_template(req, 'chtarif.html', uid=str(puser.ID), \
   mail=puser.mail, ip=puser.ip, curstate=u'Смена тарифа', menu=menu,tarifs=tarifs)
  else:
   # apply changes
   functions.chtarif(uid, tarif)
   functions.db.close()
   return functions.redirect(req, 'users')
 else:
  functions.db.close()
  return functions.use_template(req, 'admin-only.html', menu=menu, \
  curstate=u'пошёл нахуй отсюда!')

def payments(req, **params):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1: return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 menu = functions.gmenu()
 menu[1][1] = None
 menu = functions.make_menu(req, 'lpanel.html', menu)
 if user.is_admin():
  sql = 'select users.comment, date, time, s, payments.comment from payments, '+\
  'users where (to_ID=ID) order by date desc, time desc limit 100'
  pm = functions.db.query(sql).fetchall()
 else:
  sql = 'select users.comment, date, time, s, payments.comment from payments, users where '+\
  '(ID=%s) and (to_ID=ID) order by date desc, time desc limit 100'
  pm = functions.db.query(sql, (user.ID, )).fetchall()
 s = u''
 pid = 0
 for p in pm:
  pid += 1
  _ip, date, time, sum, comment = p
  sum = '%0.2f' % (float(sum), )
  s += functions.use_template(req, 'payment.html', user=functions.db.decode(_ip), uid=str(ID), \
  date=str(date), timep=str(time), s=sum, comment=functions.db.decode(comment), \
  pid=str(pid)).decode(functions.enc)
 functions.db.close()
 return functions.use_template(req, 'payments.html', pm=s, curstate=u'Список платежей', menu=menu, pcount=str(pid))

def adduser(req, login='', email='', ip='', comment='?'):
 functions.db = functions.mysql_db()
 req.headers_out.add("Cache-Control", "no-cache")
 req.headers_out.add("Expires", "-1")
 req.headers_out.add("Pragma", "no-cache")
 ID = functions.get_cookie_id(req)
 if ID < 1:
  functions.db.close()
  return functions.redirect(req, 'sign')
 # else user logged in
 user = functions.user(req, ID)
 menu = functions.gmenu()
 menu[2][1] = None
 menu = functions.make_menu(req, 'lpanel.html', menu)
 smenu = functions.make_menu(req, 'tpanel.html', [[u'Список', 'users'], [u'Добавить пользователя', None]])
 if user.is_admin():
  if not(functions.valid_login(login) and email):
   functions.db.close()
   return functions.use_template(req, 'adduser.html', curstate=u'Добавление пользователя',\
   menu=menu, submenu=smenu)
  else:
   # add user
   PASS = functions.hash_passwd(login)
   functions.db.query('insert into users(login, MAIL, PASS, BALANCE, STATUS, REGDATE, COMMENT, IP, NETUNTIL, LASTACT, TARIF) ' + \
   'values(%s, %s, %s, 0, 0, CURDATE(), %s, %s, 0, 0, 1)', (login, email, PASS, comment, ip))
   #functions.db.query('update users set IP=concat("172.17.17.", 4*ID-2)')
   functions.db_integrity()
   functions.db.commit()
   functions.db.close()
   return functions.redirect(req, 'users')
 else:
  functions.db.close()
  return functions.use_template(req, 'admin-only.html', menu=menu, \
  curstate=u'пошёл нахуй отсюда!', submenu=smenu)

def help(req):
 menu = functions.gmenu()
 menu[4][1] = None
 menu = functions.make_menu(req, 'lpanel.html', menu)
 submenu = functions.make_menu(req, 'tpanel.html', [[u'Тарифы', 'tariff'], [u'Настройка интернет', None]])
 remoteip=req.get_remote_host().split('.')[-1]
 return functions.use_template(req, 'help.html', menu=menu, \
 curstate=u'Настройка интернет', remoteip=remoteip, submenu=submenu)

def tariff(req):
 functions.db = functions.mysql_db()
 s = functions.tariffs(req)
 functions.db.close()
 return s

#def db(req):
 #s = ''
 #try: functions.db.close()
 #except: s = 'failed to close db'
 #functions.db = functions.mysql_db()
 #return s + '\n' +'reconnected'

def api(req, skey='0', inet=None):
    """inet: на сколько сек включить интернет, так что это будет типа авторизатора.
    """
    functions.db = functions.mysql_db()
    uid = functions.db.query("select ID from users where sha(concat(login, PASS))=%s", (skey, )).fetchall()
    if uid:
        uid = uid[0][0]
        if not inet is None:
            functions.db.query("update users set STATUS=1, NETUNTIL=UNIX_TIMESTAMP()+%s where ID=%s", (int(inet), uid))
            functions.update_firewall(functions.db)
        u = functions.db.query("select login, MAIL, BALANCE, IP, STATUS, LASTACT, TARIF, LASTABON, credit, prepaid from users "+\
    ", prepaid_packets where prepaid_packets.userid=users.ID and users.ID=%s and traf_id=1", (uid, )).fetchall()
        ans = "%s %s %0.2f %s %s %s %s %s %0.2f %d" % u[0]
    else:
        req.status = 403
        ans = "Forbidden"
    functions.db.commit()
    functions.db.close()
    return ans

def online_users(req):
     db = functions.mysql_db()
     u = db.query("SELECT count(*) from users WHERE LASTACT+300>%s", (functions.time(), )).fetchall()
     if u: return str(u[0][0])
     else: return '0'
     db.close()

def err404(req):
     return functions.redirect(req, "/")
